﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using PivotServerTools;

namespace CollectionFactories.TeamCity
{
    class TeamCityBuildTypesCollectionFactory : TeamCityCollectionFactoryBase<TeamCityBuildsCollectionFactory>
    {
        public TeamCityBuildTypesCollectionFactory(TeamCityBuildsCollectionFactory inner) : base(inner)
        {
        }

        public override bool CanHandle(CollectionRequestContext context)
        {
            return context.Query["type"] == "buildTypes";
        }

        protected override Collection Handle(CollectionRequestContext context, string responseString)
        {
            if (string.IsNullOrEmpty(context.Query["projectId"]))
                return ErrorCollection.FromException(new ArgumentException("If you want to see build types you need to supply a project id"));

            XDocument document;

            try
            {
                document = XDocument.Parse(responseString);
            }
            catch (Exception e)
            {
                return ErrorCollection.FromException(e);
            }

            var buildTypes = from b in document.Descendants("buildType")
                             select new
                             {
                                 Name = b.Attribute("name").Value,
                                 Id = b.Attribute("id").Value,
                                 RestUri = MakeRestUri(b.Attribute("href").Value)
                             };

            var buildTypesWithDetails = from b in buildTypes
                                        let details = XDocument.Parse(GetResponseString(string.Format("/app/rest/buildTypes/id:{0}", b.Id))).Element("buildType")
                                        select new
                                        {
                                            b.Name,
                                            b.Id,
                                            Href = b.RestUri,
                                            Url = MakeUserUri(details.Attribute("webUrl").Value),
                                            BuildsSourceUrl = MakeBuildsSourceUrl(context.Url, b.Id),
                                            Description = details.Attribute("description").Value,
                                            Paused = details.Attribute("paused").Value,
                                        };

            var collection = new Collection { Name = "TeamCity build types" };

            foreach (var buildType in buildTypesWithDetails)
            {
                collection.AddItem(buildType.Name, buildType.BuildsSourceUrl, buildType.Description, null,
                                   new Facet("Paused", FacetType.Text, buildType.Paused));
            }

            return collection;
        }

        private string MakeBuildsSourceUrl(string baseUrl, string parameter)
        {
            return Inner.CreateCollectionUri(new TeamCityAuthenticationData(this), baseUrl, parameter);
        }

        protected override string Resource(CollectionRequestContext context)
        {
            return "/app/rest/projects/id:" + context.Query["projectId"];
        }

        protected override IEnumerable<KeyValuePair<string, string>> AddCollectionUrlQueryString(string value)
        {
            yield return new KeyValuePair<string, string>("type", "buildTypes");
            yield return new KeyValuePair<string, string>("projectId", value);
        }
    }
}